package fr.ul.ade.prime.ui;

import android.content.ContentUris;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;

import fr.ul.ade.R;
import fr.ul.ade.prime.model.AdeWebOptions;
import fr.ul.ade.prime.model.Project;
import fr.ul.ade.prime.model.Schedule;
import fr.ul.ade.prime.model.ScheduleState;
import fr.ul.ade.prime.provider.AdeWebContract;

public class ScheduleDetailsFragment extends SherlockFragment implements
		LoaderManager.LoaderCallbacks<Cursor>, OnLongClickListener {
	
	protected static final String TAG = ScheduleDetailsFragment.class
			.getSimpleName();
	/**
	 * L'emploi du temps à afficher
	 */
	Schedule schedule;	
	
	public Schedule getSchedule() {
		return schedule;
	}

	public void setSchedule(Schedule schedule) {
		this.schedule = schedule;
	}

	private final ContentObserver mObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
			// Si jamais des données sont modifiées avant que le fragment soit
			// ajouté à l'activité
            if (getActivity() == null) {
                return ;
            }

            // On récupère le loader
			Loader<Cursor> loader = getLoaderManager().getLoader(
					ScheduleQuery._TOKEN);
            if (loader != null) {
            	// On force le rechargment des données.
                loader.forceLoad() ;
            }
        }
    } ;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.schedule_details, container, false) ;
        v.setOnLongClickListener(this) ;
		return v ;
	}

	private void addObserver() {
        Uri scheduleUri = AdeWebContract.Schedule.CONTENT_URI ;
		long scheduleId = ((ScheduleList) this.getActivity())
				.getDisplayedScheduleId();
		scheduleUri = ContentUris.withAppendedId(scheduleUri, scheduleId) ;
		this.getActivity().getContentResolver()
				.registerContentObserver(scheduleUri, true, this.mObserver);
	}

	private void removeObserver() {
		this.getActivity().getContentResolver()
				.unregisterContentObserver(this.mObserver);
    }
    
    @Override
    public void onHiddenChanged(boolean hidden) {
    	super.onHiddenChanged(hidden) ;
    	if (!hidden) {
    		getLoaderManager().restartLoader(ScheduleQuery._TOKEN, null, this) ;
    		this.addObserver() ;
    	} else {
    		getLoaderManager().destroyLoader(ScheduleQuery._TOKEN) ;
    		this.removeObserver() ;
    	}// if
    }
    
	private void bindView(View view, Context context, Cursor cursor) {
		TextView tv ;
		String str ;
		
		Project project = new Project(
				cursor.getInt(ScheduleQuery.SCHEDULE_PROJECT_ID),
				cursor.getString(ScheduleQuery.SCHEDULE_PROJECT_NAME));
		schedule = new Schedule(project,
				cursor.getString(ScheduleQuery.SCHEDULE_NAME),
				cursor.getString(ScheduleQuery.SCHEDULE_RESOURCES),
				cursor.getInt(ScheduleQuery.SCHEDULE_SUB_PERIOD),
				cursor.getString(ScheduleQuery.SCHEDULE_LAST_UPDATE),
				ScheduleState.WAITING_FOR_UPDATE,
				cursor.getString(ScheduleQuery.SCHEDULE_CREATED),
				cursor.getString(ScheduleQuery.SCHEDULE_STUDENT_NUM));
		
		//on fixe le champ displayedSchedule dans ScheduleList
		((ScheduleList) this.getActivity()).setDisplayedSchedule(schedule);

		// Schedule name
		tv = (TextView) view.findViewById(R.id.schedule_details_name) ;
		tv.setText(schedule.getName());

		// Last updated
		tv = (TextView) view.findViewById(R.id.schedule_details_last_update) ;
		try {
			str = schedule.getLastUpdate();
			if (!TextUtils.isEmpty(str) && !str.equals("null")) {
				tv.setText(str) ;
			} else {
				tv.setText(R.string.ScheduleDetails_never) ;
			}
		} catch (Exception e) {
			tv.setText(R.string.ScheduleDetails_never) ;
		}
		
		// Resource
		tv = (TextView) view.findViewById(R.id.schedule_details_resources) ;
		StringBuilder resources = new StringBuilder() ;
		try {
			str = schedule.getResources();
			if (!TextUtils.isEmpty(str) && !str.equals("null")) {
				resources.append("|") ;
				resources.append(str) ;
			}
		} catch (Exception e) {
		}
		try {
			str = schedule.getStudentNum();
			if (!TextUtils.isEmpty(str) && !str.equals("null")) {
				resources.append("|") ;
				resources.append(str) ;
			}
		} catch (Exception e) {
		}
		if (resources.length() == 0) {
			resources.append("|") ;
		}
		tv.setText(resources.substring(1)) ;
		
		// Period
		tv = (TextView) view.findViewById(R.id.schedule_details_period) ;
		String periodTemplate = context.getResources().getString(
				R.string.ScheduleDetails_period_template) ;
		tv.setText(String.format(periodTemplate, schedule.getPeriod()));

		// Project Id
		tv = (TextView) view.findViewById(R.id.schedule_details_project_id) ;
		tv.setText(schedule.getProject().getProjectName());
		
		// Creation date
		tv = (TextView) view.findViewById(R.id.schedule_details_created) ;
		tv.setText(schedule.getCreated());
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Uri scheduleUri = AdeWebContract.Schedule.CONTENT_URI ;
		long scheduleId = ((ScheduleList) this.getActivity())
				.getDisplayedScheduleId();
		scheduleUri = ContentUris.withAppendedId(scheduleUri, scheduleId) ;
		String[] projection = ScheduleQuery.PROJECTION ;
		String selection = null ;
		String[] selectionArgs = null ;
		
//		Log.d(TAG, "[onCreateLoader]: "+scheduleUri) ;
		return new CursorLoader(this.getActivity(), scheduleUri, projection,
				selection, selectionArgs, AdeWebContract.Schedule.DEFAULT_SORT);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if (this.getActivity() == null) {
			return ;
		}
		this.getView().setBackgroundColor(AdeWebOptions.getBackgroundColor(AdeWebOptions.getTheme(this.getActivity())));
		if (cursor.moveToFirst()) {
			bindView(this.getView(), this.getActivity(), cursor) ;
		} else {
			Log.d(TAG, "Erreur: edt inexistant !") ;
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		/* Nothing to be done. */
	}

	@Override
	public boolean onLongClick(View v) {
//		FragmentManager fm = this.getActivity().getSupportFragmentManager() ;
//		Fragment detailsFragment = fm.findFragmentById(R.id.schedule_details) ;
//		Fragment listFragment = fm.findFragmentById(R.id.schedule_list) ;
//		FragmentTransaction ft = fm.beginTransaction() ;
//		ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out) ;
//		ft.hide(detailsFragment) ;
//		ft.show(listFragment) ;
//		ft.commit() ;
		
		ScheduleList activity = (ScheduleList) this.getActivity() ;
		activity.mActionMode.finish();

		return true ;
	}
	
	protected interface ScheduleQuery {
		// id pour le loader
		int _TOKEN = 0x1 ;
		
		// colonnes demandés au provider
		String[] PROJECTION = {
			BaseColumns._ID,
			AdeWebContract.Schedule.SCHEDULE_NAME,
			AdeWebContract.Schedule.SCHEDULE_LAST_UPDATE,
			AdeWebContract.Schedule.SCHEDULE_RESOURCES,
			AdeWebContract.Schedule.SCHEDULE_STUDENT_NUM,
			AdeWebContract.Schedule.SCHEDULE_PERIOD,
			AdeWebContract.Schedule.SCHEDULE_PROJECT_ID,
			AdeWebContract.Schedule.SCHEDULE_PROJECT_NAME,
			AdeWebContract.Schedule.SCHEDULE_CREATED
		} ;
		
		// colonnes des données demandés pour utiliser lors de la récupération
		// des données depuis le Cursor (appels à getString(int) p.ex.)
		int _ID = 0 ;
		int SCHEDULE_NAME = 1 ;
		int SCHEDULE_LAST_UPDATE = 2 ;
		int SCHEDULE_RESOURCES = 3 ;
		int SCHEDULE_STUDENT_NUM = 4 ;
		int SCHEDULE_SUB_PERIOD = 5 ;
		int SCHEDULE_PROJECT_ID = 6;
		int SCHEDULE_PROJECT_NAME = 7;
		int SCHEDULE_CREATED = 8;
	}
	
}// class ScheduleDetailsFragment